var utils = {
  sleep_and_log(duration) {
    var interval = 5;
    while (duration > interval) {
      sleep(interval * 1000);
      duration = duration - interval;
      console.log("还剩:" + duration + "s");
    }
    if (duration > 0) {
      sleep(duration * 1000);
      console.log("sleep_and_log: duration ", duration, "s");
    }
  },
  click_text(content) {
    if (this.exists_text(content)) {
      var uiText = text(content).findOne();
      var bounds = uiText.bounds();
      click(bounds.centerX(), bounds.centerY());
      return uiText;
    } else {
      return false;
    }
  },
  click_text_starts_with(content) {
    if (this.exists_text_starts_with(content)) {
      var uiText = textStartsWith(content).findOne();
      var bounds = uiText.bounds();
      click(bounds.centerX(), bounds.centerY());
      return uiText;
    } else {
      return false;
    }
  },
  exists_text(content) {
    if (text(content).exists()) {
      return text(content).findOne();
    } else {
      return false;
    }
  },
  exists_text_starts_with(content) {
    if (textStartsWith(content).exists()) {
      return textStartsWith(content).findOne();
    } else {
      return false;
    }
  },
  get_center_point(x1, y1, x2, y2) {
    return {
      x: x1 + (x2 - x1) / 2,
      y: y1 + (y2 - y1) / 2,
    };
  },
  click_point(x1, y1, x2, y2) {
    var point = this.get_center_point(x1, y1, x2, y2);
    return click(point.x, point.y);
  },
  click_bounds(bounds) {
    click(bounds.centerX(), bounds.centerY());
  },
  click_ui(ui_item) {
    while (true) {
      if (ui_item && ui_item.clickable()) {
        ui_item.click();
        return true;
      } else if (ui_item) {
        ui_item = ui_item.parent();
      } else {
        return false;
      }
    }
  },
  click_x_y(x, y) {
    click(x, y);
  },
  swipe_up(duration, distance) {
    while (duration > 3) {
      swipe(
        device.width / 2,
        device.height / 2,
        device.width / 2,
        device.height / 2 - distance,
        500 + random(0, 10)
      );
      var interval = 1 + random(0, 2);
      sleep(interval * 1000);
      duration = duration - interval;
    }
    if (duration > 0) {
      sleep(duration * 1000);
    }
    utils.toast("swipe_up end");
  },
  toast(content) {
    console.log(content);
    toast(content);
    sleep(6 * 1000);
  },
  sleep(duration) {
    var duration = duration / 1000;
    while (duration > 4) {
      sleep(4 * 1000);
      duration = duration - 4;
    }
    if (duration > 0) {
      sleep(duration * 1000);
    }
  },
  get_gold(content) {
    var reg_exp = /(\d+)/g;
    var gold_match = content.match(reg_exp);
    var gold = parseInt(gold_match ? gold_match[0] : 0);
    return gold;
  },
  get_size_point(points) {
    var length = points.length;
    var size_point = [];
    var rate_x = device.width / 720;
    var rate_y = device.height / 1650;
    for (var i = 0; i < length; i++) {
      var x_y = points[i];
      var rate = i % 2 == 0 ? rate_x : rate_y;
      size_point.push(parseInt(x_y * rate));
    }
    return size_point;
  },
  get_size_point_red_mi(points) {
    var length = points.length;
    var size_point = [];
    var rate_x = device.width / 1080;
    var rate_y = device.height / 2340;
    for (var i = 0; i < length; i++) {
      var x_y = points[i];
      var rate = i % 2 == 0 ? rate_x : rate_y;
      size_point.push(parseInt(x_y * rate));
    }
    return size_point;
  },
};

var constant = {
    min_ad_time: 40, //最小广告时间
    min_ad_swipe_time: 10, //最小广告【查看详情】滑动时间
    min_ad_after_time: 5, //判断下一个广告前的等待时间
    min_click_after_time: 2, //页面点击之后，进行下一步操作之前的等待时间
    min_gold: 0, //最小金币数量
    read_start_index: 5, //首页阅读，从第几个开始
    read_times: 2, //阅读一篇文章的下拉次数
    video_times: 20, //看视频总的下拉次数
  };
  
var point_map = {
    首页视频: [147, 1534, 278, 1618],
    首页百度: [16, 1534, 147, 1618],
    首页任务: [278, 1534, 441, 1618],
    进入任务之后的关闭: [582, 518, 606, 542],
    开宝箱之后的关闭: [550, 288, 606, 344],
    开福袋之后的关闭: [632, 344, 686, 400],
    看广告赚钱: [52, 910, 202, 942],
  };
  


var ad_util_is_to_continue = null;
var ad_util_to_continue = null;
var ad_util = {
  sleep_and_log(duration) {
    var interval = 2;
    for (; duration > interval; duration -= interval) {
      if (utils.exists_text_starts_with("已领取")) {
        var after_interval = random(3, 6);
        console.log(
          "ad_util sleep_and log: 找到【已领取】,再过" +
            after_interval +
            "s后停止当前广告"
        );
        sleep(after_interval * 1000);
        return;
      } else {
        console.log("ad_util sleep_and log: 没找到【已领取】");
      }
      if (utils.exists_text_starts_with("已完成任务")) {
        var after_interval = random(3, 6);
        console.log(
          "ad_util sleep_and log: 找到【已完成任务】,再过后" +
            after_interval +
            "s后停止当前广告"
        );
        sleep(after_interval * 1000);
        return;
      } else {
        console.log("ad_util sleep_and log: 没找到【已完成任务】");
      }
      sleep(interval * 1000);
      console.log("ad_util sleep_and log: 还剩:" + (duration - interval) + "s");
    }
    if (duration > 0) {
      sleep(duration * 1000);
      console.log("ad_util sleep_and log: duration ", duration, "s");
    }
  },
  run() {
    var ad_interval = constant.min_ad_time + random(1, 3);
    this.sleep_and_log(ad_interval);
    console.log("ad_util execute: end");
    this.go_back();
    this.after();
  },
  execute(is_to_continue, to_continue) {
    ad_util_is_to_continue = is_to_continue;
    ad_util_to_continue = to_continue;
    console.show();
    sleep(1 * 1000);
    this.run();
  },
  go_back() {
    var index = 0;
    while (true) {
      if (index > 3) {
        return;
      }
      back();
      sleep(constant.min_click_after_time * 1000);
      if (utils.exists_text_starts_with("看视频赚")) {
        return;
      }
      if (utils.exists_text_starts_with("看文章赚金币")) {
        return;
      }
      if (utils.exists_text_starts_with("立即收下")) {
        return;
      }
      if (utils.exists_text_starts_with("开心收下")) {
        return;
      }
      if (utils.exists_text_starts_with("残忍离开")) {
        return;
      }
      if (utils.exists_text_starts_with("换个视频")) {
        return;
      }
      if (utils.exists_text_starts_with("再看一个领取")) {
        return;
      }
      if (utils.exists_text_starts_with("再看一条领取")) {
        return;
      }
      if (utils.exists_text_starts_with("再看1个获得")) {
        return;
      }
      if (
        utils.exists_text_starts_with("百度") &&
        utils.exists_text_starts_with("视频") &&
        utils.exists_text_starts_with("小说")
      ) {
        console.log("go_back 找到【百度】【视频】【小说】");
        return;
      }
      if (utils.exists_text_starts_with("面对面")) {
        console.log("go_back 找到【面对面】");
        return;
      }
      if (utils.exists_text_starts_with("拒绝")) {
        utils.click_text("拒绝");
        console.log("go_back 找到【拒绝】");
        sleep(constant.min_click_after_time * 1000);
        back();
        sleep(constant.min_click_after_time * 1000);
      }
      index++;
      console.log("go_back index: ", index);
    }
  },
  after() {
    sleep(constant.min_ad_after_time * 1000);
    var ui_text_1 = utils.exists_text_starts_with("换个视频");
    if (ui_text_1) {
      console.log("gold_video after: 找到【换个视频】");
      utils.click_text_starts_with("换个视频");
      sleep(constant.min_click_after_time * 1000);
      this.run();
      return;
    }
    var ui_text_2 = utils.exists_text_starts_with("再看一个领取");
    if (ui_text_2) {
      console.log("ad_util after: 找到【再看一个领取】" + ui_text_2.text());
      var gold = utils.get_gold(ui_text_2.text());
      console.log("ad_util after: " + gold + "金币");
      utils.click_text_starts_with("再看一个领取");
      sleep(constant.min_click_after_time * 1000);
      this.run();
      return;
    }
    var ui_text_3 = utils.exists_text_starts_with("再看1个获得");
    if (ui_text_3) {
      console.log("ad_util after: 找到【再看1个获得】");
      utils.click_text_starts_with("再看1个获得");
      sleep(constant.min_click_after_time * 1000);
      this.run();
      return;
    }
    var ui_text_4 = utils.exists_text_starts_with("再看一条领取");
    if (ui_text_4) {
      console.log("ad_util after: 找到【再看一条领取】" + ui_text_4.text());
      var gold = utils.get_gold(ui_text_4.text());
      console.log("ad_util after: " + gold + "金币");
      utils.click_text_starts_with("再看一条领取");
      sleep(constant.min_click_after_time * 1000);
      this.run();
      return;
    }
    console.log(
      "ad_util after: 没找到【再看一个领取】或【再看1个获得】或【换个视频】或【再看一条领取】"
    );
    if (ad_util_is_to_continue && ad_util_is_to_continue()) {
      //是否有下一步
      ad_util_to_continue && ad_util_to_continue();
    } else {
      this.next();
    }
  },
  next() {
    console.hide();
    sleep(1 * 1000);
    console.log("ad_util next");
  },
};



if (!requestScreenCapture()) {
  toastLog("请求截图权限失败");
  exit();
}
var char_match_map = {
  搜: ["嫂", "樓", "接", "楼"],
  赚: ["廉", "嫌", "賺", "兼"],
  看: ["着", "春"],
  文: ["女"],
  章: ["拿"],
  钱: ["线"],
  觉: ["党"],
  户: ["戶"],
  索: ["素"],
  开: ["升", "研"],
  金: ["全"],
  积: ["枳"],
  币: ["市"],
  现: ["現"],
  领: ["領"],
  读: ["渎"],
  额: ["額"],
  取: ["驭"],
  视: ["规"],
};

var ocrUtils = {
  get_reg_exp(content) {
    var reg_exp_string = content
      .split("")
      .map(function (item) {
        var match = char_match_map[item];
        var piece = match
          ? "[" + match.concat(item).join("") + "]+"
          : "[" + item + "]+";
        return piece + `\\s*`;
      })
      .join("");
    var reg_exp = new RegExp(reg_exp_string, "gi");
    console.log("ocrUtils get_reg_exp:", reg_exp.toString());
    return reg_exp;
  },
  capture_screen_then_log_text() {
    var capture_img = captureScreen();
    var capture_img_orc_result = gmlkit.ocr(capture_img, "zh").toArray(3);
    for (var i = 0; i < capture_img_orc_result.length; i++) {
      var item = capture_img_orc_result[i];
      console.log(item.text);
    }
  },
  capture_screen_then_find_by_text(content) {
    return this.capture_screen_then_find_by_reg_exp(this.get_reg_exp(content));
  },
  capture_screen_then_find_by_reg_exp(reg_exp) {
    var capture_img = captureScreen();
    if (!capture_img) {
      toastLog("截图失败");
    }
    var capture_img_orc_result = gmlkit.ocr(capture_img, "zh").toArray(3);

    for (var i = 0; i < capture_img_orc_result.length; i++) {
      var item = capture_img_orc_result[i];
      if (reg_exp.test(item.text)) {
        return item;
      }
    }
  },
  find_text(content) {
    var max_swipe_times = 10;
    var reg_exp = this.get_reg_exp(content);
    while (max_swipe_times > 0) {
      var result = this.capture_screen_then_find_by_reg_exp(reg_exp);
      if (result) {
        return result;
      }
      swipe(
        device.width / 2,
        device.height / 2,
        device.width / 2,
        device.height / 2 - 200,
        500
      );
      max_swipe_times -= 1;
    }
  },
};

//随机搜 30次
var search30 = {
  is_first_back: true,
  go_page_from_home() {},
  start() {
    console.log("search30: start");
    this.init();
  },
  init() {
    // 2704
    console.show();
    sleep(1 * 1000);
    var result = ocrUtils.find_text("随机搜赚钱");
    if (result) {
      var x = result.bounds.centerX();
      var y = result.bounds.centerY();
      console.log("找到【随机搜赚钱】", "坐标：x: " + x + " y: " + y);
      for (var i = 0; i < 30; i++) {
        utils.click_x_y(x, y);
        sleep(constant.min_click_after_time * 1000);
        var search_swipe_times = 6 + random(0, 2);
        console.log("即将开始滑动--" + search_swipe_times + "--次");
        sleep(1 * 1000);
        while (search_swipe_times > 0) {
          swipe(
            device.width / 2,
            (device.height / 10) * 5,
            device.width / 2,
            (device.height / 10) * 2,
            500
          );
          var watch_search_result_time = 3 + random(0, 2);
          sleep(watch_search_result_time * 1000);
          search_swipe_times = search_swipe_times - 1;
        }
        back();
        if (this.is_first_back) {
          sleep(5 * 1000);
        } else {
          sleep(2 * 1000);
        }
        if (this.is_first_back && utils.click_text_starts_with("残忍离开")) {
          this.is_first_back = false;
          console.log("找到--残忍离开--");
        } else {
          console.log("没找到--残忍离开--");
        }
        sleep(2 * 1000);
      }
    } else {
      console.log("没找到【随机搜赚钱】");
    }

    console.hide();
    sleep(1 * 1000);
  },
  next() {
    console.log("ad: next");
  },
};

//搜一搜赚钱 2次
var search2 = {
  is_first_back: true,
  go_page_from_home() {},
  start() {
    console.log("search2: start");
    this.init();
  },
  init() {
    // 2704
    console.show();
    sleep(1 * 1000);
    var result = ocrUtils.find_text("搜一搜赚钱");
    if (result) {
      var x = result.bounds.centerX();
      var y = result.bounds.centerY();
      console.log("找到【搜一搜赚钱】", "坐标：x: " + x + " y: " + y);
      for (var i = 0; i < 2; i++) {
        utils.click_x_y(x, y);
        sleep(constant.min_click_after_time * 1000);
        utils.click_point.apply(
          utils,
          utils.get_size_point_red_mi([871, 141, 1025, 212])
        );
        sleep(constant.min_click_after_time * 1000);
        var search_swipe_times = 6 + random(0, 2);
        console.log("即将开始滑动--" + search_swipe_times + "--次");
        sleep(1 * 1000);
        while (search_swipe_times > 0) {
          swipe(
            device.width / 2,
            (device.height / 10) * 5,
            device.width / 2,
            (device.height / 10) * 2,
            500
          );
          var watch_search_result_time = 3 + random(0, 2);
          sleep(watch_search_result_time * 1000);
          search_swipe_times = search_swipe_times - 1;
        }
        back();
        if (this.is_first_back) {
          sleep(5 * 1000);
        } else {
          sleep(2 * 1000);
        }
        if (this.is_first_back && utils.click_text_starts_with("残忍离开")) {
          this.is_first_back = false;
          console.log("找到--残忍离开--");
        } else {
          console.log("没找到--残忍离开--");
        }
        sleep(2 * 1000);
      }
    } else {
      console.log("没找到【搜一搜赚钱】");
    }

    console.hide();
    sleep(1 * 1000);
  },
  next() {
    console.log("ad: next");
  },
};

var shop = {
  times: 7,
  go_page_from_home() {},
  init() {},
  start() {
    console.log("shop start");
    if (this.times < 10) {
      this.execute();
    } else {
      this.next();
    }
  },
  execute() {
    var swipe_times = 15 + random(0, 3);
    console.log("即将开始滑动" + swipe_times + "次");
    for (var j = 0; j < swipe_times; j++) {
      swipe(
        device.width / 2,
        (device.height / 10) * 5,
        device.width / 2,
        (device.height / 10) * 2,
        500
      );
      var swipe_after_interval = 3 + random(0, 2);
      console.log(
        "第" +
          (j + 1) +
          "次滑动完成，等待" +
          swipe_after_interval +
          "秒后开始下一次滑动"
      );
      sleep(swipe_after_interval * 1000);
      if (utils.exists_text_starts_with("看视频再得")) {
        console.log("shop execute: 找到--看视频再得--,本次浏览已完成");
        break;
      }
    }
    this.after();
  },
  after() {
    console.log("shop after");
    this.times = this.times + 1;
    if (utils.click_text_starts_with("看视频再得")) {
      console.log("shop after: 找到--看视频再得--");
      sleep(constant.min_click_after_time * 1000);
      sleep(25 * 1000);
      back();
      sleep(2 * 1000);
      if (utils.exists_text_starts_with("恭喜你获得")) {
        console.log("shop after: 找到--恭喜你获得--");
        sleep(constant.min_click_after_time * 1000);
        utils.click_point(488, 1537, 592, 1640);
        sleep(constant.min_click_after_time * 1000);
      }
    }
    console.log("shop after: 已经浏览本页" + this.times + "次");
    if (this.times < 10) {
      var wait_next_interval = 20 + random(0, 3);
      console.log(
        "shop after: 等待" + wait_next_interval + "秒，开始下一次浏览本页"
      );
      sleep(wait_next_interval * 1000);
      this.execute();
      return;
    }
    this.next();
  },
  next() {
    console.log("next");
  },
};

function main() {
      var index = 0;
      while (true) {
        if (index > 100) {
          return;
        }
        video.go_page_from_home();
        sleep(2 * 1000);
        treasure.go_page_from_home();
        sleep(2 * 1000);
        ad.go_page_from_home();
        sleep(2 * 1000);
        console.show();
        console.log("在等待下一个轮回,5s");
        sleep(5 * 1000);
        console.hide();
        sleep(2 * 1000);
        index = index + 1;
      }
    }
    main();